package com.kong.mobile.controller;

import com.aliyuncs.exceptions.ClientException;
import com.kong.constant.MessageConstant;
import com.kong.constant.RedisConstant;
import com.kong.entity.Result;
import com.kong.utils.SMSUtils;
import com.kong.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author yang2013
 * @data 2020/10/15 15:09
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;


    /**
     * 发送验证码 通过redis获取的值判断验证码是否过期---过期就重新发送并存储
     * @param telephone
     * @return
     */
    @PostMapping("/send4order")
    public Result send4order(String telephone){
        Jedis jedis = jedisPool.getResource();
        String tag=RedisConstant.SENDTYPE_ORDER + "_" + telephone;
        String value = jedis.get(tag);
        if (StringUtils.isEmpty(value)){
            try {
                //生成六位随机数
                int code = ValidateCodeUtils.generateValidateCode(6);

                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,String.valueOf(code));
                //存入redis
                jedis.setex(tag,10*24*60*60,String.valueOf(code));

                return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
            } catch (ClientException e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
            }
        }
        return new Result(false,MessageConstant.SENT_VALIDATECODE);
    }
}
